import 'dart:typed_data';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_news/model/news_detail_model.dart';
import 'package:aichat_flutter_wallet/module/module_news/model/remark_item.dart';
import 'package:aichat_flutter_wallet/module/module_news/utils/news_util.dart';
import 'package:aichat_flutter_wallet/module/module_news/widget/new_detail_remark_h1.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_api.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_network/http_manager.dart';

import '../../../module_common/bridge/native_channel_bridge.dart';

class NewsProvider extends ChangeNotifier {
  List<RemarkItem> remark_item_list = [];
  NewsDetailModel? newsDetailModel;
  int targetType = 0;
  String articleId = '';
  bool isEnd = false;

  setTargetType(int type,String id){
    targetType=type;
    articleId=id;
  }

  // 设置详情/
  setDetail(NewsDetailModel? detail) {
    newsDetailModel = detail;
    notifyListeners();
  }

  // 设置评论列表
  setRemarkList(List<RemarkItem> list) {
    remark_item_list = [...remark_item_list, ...list];
    notifyListeners();
  }
  // 设置评论列表
  setRemarkListNone() {
    remark_item_list = [];
    notifyListeners();
  }

  // 添加一级评论
  addOneRemarkList(RemarkItem remark) {
    remark_item_list = [remark, ...remark_item_list];
    notifyListeners();
  }

  // 点赞，取消点赞
  doLike(
      {required String target_id,
      required int target_type,
      int like_status = 1,
      required Function beforeCall,
      required Function failCall}) {
    bool is_like = false;

    if (like_status == 0) {
      is_like = true;
    }
    beforeCall(is_like);

    HttpManager().post(API.doLike, {
      "target_id": target_id,
      "target_type": target_type,
      "op": is_like ? "1" : '0'
    }).then((value) {
      if (value!.code == 0) {
        NativeChannelBridge().flGoCommentSuccess(target_type.toString(),target_id.toString(),'like',count: is_like ? -1 : 1);
      } else {
        failCall(is_like);
      }
    });
  }

  // 评论
  doComment(
      {int? target_type,
      String? article_id,
      String? target_id,
      int level = 1,
      List<String>? images,
      List<String>? videos,
      RemarkItem? item,
      String? content,
      Function? success,
      Function? fail}) {
   HttpManager().post(API.doComment, {
      'content': content != null
          ? content
          : 'time ：${DateTime.now().toString()}',
      "target_type": target_type,
      'article_id': article_id,
      "target_id": target_id != null ? target_id : '',
      'type': 0,
      "images": images != null
          ? images
          : [
              'https://cdn.pixabay.com/photo/2023/06/13/11/45/landscape-8060760_1280.jpg'
            ],
      'videos': videos != null
          ? videos
          : [
              'https://vd2.bdstatic.com/mda-qanbeuph19kxqn0y/576p/h264/1705997964665231184/mda-qanbeuph19kxqn0y.mp4?v_from_s=hkapp-haokan-hbf&auth_key=1710398883-0-0-e561f9daaf8a3faa4ea84d91f9e1e36f&bcevod_channel=searchbox_feed&pd=1&cr=1&cd=0&pt=4&logid=2883730566&vid=5061286747884'
            ]
    }).then((value) {
      if (success != null) {
        success(value);
      }
    }).catchError((error){
      kaiPrint('error $error');
   })
       .onError((error, stackTrace) {
      if (fail != null) {
        fail(error);
      }
    });
  }

  // 获取评论组件列表
  List<Widget> getH1CommentWidget() {
    List<Widget> list = [];
    if (remark_item_list.isNotEmpty) {
      remark_item_list.forEach((element) {
        list.add(
          NewDetailRemarkH1(
            key: ValueKey(element.id), // 保证组件的唯一性
            item: element,
            article_id: newsDetailModel!.id,
          ),
        );
      });
      return list;
    }
    return [];
  }

  // 获取video的组件
  Widget getVideoWidget({required Uint8List videoImg, VoidCallback? callback}) {
    Widget widget = InkWell(
        splashColor: Colors.transparent,
        onTap: () {
          if (callback != null) {
            callback();
          }
        },
        child: Container(
          width: double.infinity,
          margin: EdgeInsets.only(top: 20),
          height: 164.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
          ),
          child: Stack(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Image.memory(
                  videoImg,
                  width: double.infinity,
                  height: 164.h,
                  scale: 1,
                  fit: BoxFit.cover,
                ),
              ),
              Container(
                alignment: Alignment.center,
                child: PublicImage(
                  image: 'assets/images/common/play.png',
                  width: 50.w,
                  height: 40.h,
                ),
              ),
            ],
          ),
        ));

    return widget;
  }

  // 评论区域
  Widget getRemarkFooter(RemarkItem remarkItem,
      {Function? doComment, Function? doLike}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          remarkItem.created_at.isNotEmpty
              ? NewsUtil.transDate(remarkItem.created_at)
              : '------',
          style: TextStyle(fontSize: 12.sp, color: AppColors.c_BEBDCA),
        ),
        Row(
          children: [
            InkWell(
              splashColor: Colors.transparent,
              onTap: () {
                if (doComment != null) {
                  doComment(remarkItem);
                }
              },
              child: Row(
                children: [
                  PublicImage(
                    image: 'assets/images/common/news_remark.png',
                    height: 16.w,
                    width: 16.w,
                  ),
                  SizedBox(
                    width: 5.w,
                  ),
                  Text(
                    '${remarkItem.comment_count}',
                    style:
                        TextStyle(fontSize: 12.sp, color: AppColors.c_868391),
                  )
                ],
              ),
            ),
            SizedBox(
              width: 20.w,
            ),
            InkWell(
              splashColor: Colors.transparent,
              onTap: () {
                if (doLike != null) doLike(remarkItem);
              },
              child: Row(
                children: [
                  PublicImage(
                    image: remarkItem.like_status == 1
                        ? 'assets/images/common/news_like.png'
                        : 'assets/images/common/news_like_active.png',
                    height: 16.w,
                    width: 16.w,
                  ),
                  SizedBox(
                    width: 5.w,
                  ),
                  Text(
                    '${remarkItem.like_count}',
                    style:
                        TextStyle(fontSize: 12.sp, color: AppColors.c_868391),
                  )
                ],
              ),
            ),
            SizedBox(
              height: 12.h,
            ),
          ],
        )
      ],
    );
  }
}
